package com.wangsd.system.service;

import com.gitee.fastmybatis.core.query.Query;
import com.wangsd.common.constants.ButtonType;
import com.wangsd.system.entity.SysMenu;
import com.wangsd.system.mapper.SysMenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 菜单Service业务层处理
 *
 * @author wsd
 * @date 2021-03-16
 */
@Service
public class SysMenuService {
    @Autowired
    private SysMenuMapper sysMenuMapper;

    /**
     * 查询菜单
     *
     * @param id 菜单ID
     * @return 菜单
     */
    public SysMenu selectSysMenuById(Long id) {
        return sysMenuMapper.getById(id);
    }

    /**
     * 查询菜单列表
     *
     * @return 菜单
     */
    public List<SysMenu> selectSysMenuList() {
        List<SysMenu> parentList = selectMenuByType(1);
        List<SysMenu> childList = selectMenuByType(2);
        List<SysMenu> sysbuttonList = selectMenuByType(3);


        Map<Long, List<SysMenu>> childMap = childList.stream().collect(Collectors.groupingBy(SysMenu::getPid));

        Map<Long, List<SysMenu>> buttonMap = sysbuttonList.stream().collect(Collectors.groupingBy(SysMenu::getPid));

        for (SysMenu sysMenu : parentList) {
            /*取出父菜单下的所有子菜单*/
            List<SysMenu> child = childMap.get(sysMenu.getId());
            List<SysMenu> childMenuList = new ArrayList<>();
            if (child == null) {
                continue;
            }
            for (SysMenu menu : child) {
                /*取出子菜单所对应的按钮*/
                List<SysMenu> buttonList = buttonMap.get(menu.getId());
                //放按钮权限集
                if (buttonList != null) {
                    List<String> actions = buttonList.stream().map(SysMenu::getKeySign).collect(Collectors.toList());
                    menu.setActions(actions);
                    menu.setButtonList(buttonList);
                } else {
                    menu.setActions(new ArrayList<>());
                    menu.setButtonList(new ArrayList<>());
                }
                childMenuList.add(menu);
            }
            sysMenu.setChildren(childMenuList);
        }
        return parentList;
    }

    /**
     * 新增菜单
     *
     * @param sysMenu 菜单
     * @return 结果
     */
    @Transactional
    public void insertSysMenu(SysMenu sysMenu) {
        sysMenuMapper.saveIgnoreNull(sysMenu);
        insertButton(sysMenu);
    }

    /**
     * 修改菜单
     *
     * @param sysMenu 菜单
     * @return 结果
     */
    @Transactional
    public void updateSysMenu(SysMenu sysMenu) {
        sysMenuMapper.updateIgnoreNull(sysMenu);
        insertButton(sysMenu);
    }

    /**
     * 删除菜单信息
     *
     * @param id 菜单ID
     * @return 结果
     */
    @Transactional
    public int deleteSysMenuById(Long id) {
        SysMenu sysMenu = selectSysMenuById(id);
        if (sysMenu.getMenuType() == 1) {
            Query query1 = new Query();
            query1.eq("pid", id);
            List<SysMenu> list = sysMenuMapper.list(query1);
            //删除第三级
            List<Long> ids = list.stream().map(SysMenu::getId).collect(Collectors.toList());
            Query query2 = new Query();
            query2.in("pid", ids);
            sysMenuMapper.deleteByQuery(query2);
        }
        //删除直接下级
        Query query3 = new Query();
        query3.eq("pid", id);
        sysMenuMapper.deleteByQuery(query3);

        return sysMenuMapper.deleteById(id);
    }

    /**
     * 新增按钮
     *
     * @param sysMenu
     */
    private void insertButton(SysMenu sysMenu) {
        List<String> actions = sysMenu.getActions();
        if (sysMenu.getMenuType() == 2 && actions != null && actions.size() > 0) {
            //删除所有按钮
            sysMenuMapper.deleteByQuery(new Query().eq("pid", sysMenu.getId()));
            List<SysMenu> buttonList = new ArrayList<>();
            for (String item : actions) {
                SysMenu entity = new SysMenu();
                entity.setMenuName(ButtonType.getValueByCode(item));
                entity.setPid(sysMenu.getId());
                entity.setKeySign(item);
                entity.setMenuType(3);
                buttonList.add(entity);
            }
            sysMenuMapper.saveBatch(buttonList);
        }
    }

    /**
     * 根据菜单类型查询
     *
     * @return
     */
    public List<SysMenu> selectMenuByType(int menuType) {
        Query query = new Query();
        query.eq("menu_type", menuType);
        List<SysMenu> list = sysMenuMapper.list(query);
        return list;
    }

    /**
     * 角色编辑查询该角色现有哪些权限
     *
     * @param roleId
     * @return
     */
    public List<SysMenu> selectSysMenuByRoleId(Long roleId) {
        Query query = new Query();
        query.join("join sys_role_menu t2 on t.id = t2.menu_id");
        query.eq("t2.role_id", roleId);
        query.in("t.menu_type", new Integer[]{1, 2});
        List<SysMenu> list = sysMenuMapper.list(query);

        Query query2 = new Query();
        query2.join("join sys_role_menu t2 on t.id = t2.menu_id");
        query2.eq("t2.role_id", roleId);
        return zuzhuangAction(list, query2);
    }

    /**
     * 查询用户拥有哪些菜单权限
     *
     * @param userId
     * @return
     */
    public List<SysMenu> selectSysMenuByUserId(Long userId) {
        Query query = new Query();
        if (userId != null) {
            query.join("join sys_role_menu t2 on t.id = t2.menu_id");
            query.join("join sys_user_role t3 on t2.role_id = t3.role_id");
            query.join("join sys_user t4 on t4.id = t3.user_id");
            query.eq("t4.id", userId);
        }
        query.in("t.menu_type", new Integer[]{1, 2});
        List<SysMenu> list = sysMenuMapper.list(query);

        Query query2 = new Query();
        if (userId != null) {
            query2.join("join sys_role_menu t2 on t.id = t2.menu_id");
            query2.join("join sys_user_role t3 on t2.role_id = t3.role_id");
            query2.join("join sys_user t4 on t4.id = t3.user_id");
            query2.eq("t4.id", userId);
        }
        return zuzhuangAction(list, query2);
    }

    /**
     * 组装数据
     *
     * @param query
     * @return
     */
    private List<SysMenu> zuzhuangAction(List<SysMenu> list, Query query) {
        query.eq("t.menu_type", 3);
        List<SysMenu> sysbuttonList = sysMenuMapper.list(query);

        Map<Long, List<SysMenu>> buttonMap = sysbuttonList.stream().collect(Collectors.groupingBy(SysMenu::getPid));

        for (SysMenu menu : list) {
            /*取出子菜单所对应的按钮*/
            List<SysMenu> buttonList = buttonMap.get(menu.getId());
            //放按钮权限集
            if (buttonList != null) {
                List<String> actions = buttonList.stream().map(SysMenu::getKeySign).collect(Collectors.toList());
                menu.setActions(actions);
            } else {
                menu.setActions(new ArrayList<>());
            }
        }
        return list;
    }
}
